package com.example.swd1.gudong.main.user.historyrecord;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.example.swd1.gudong.R;
import com.example.swd1.gudong.Tool.DatabaseHelper;
import com.example.swd1.gudong.constant.Constant;
import com.example.swd1.gudong.model.Record;
import com.example.swd1.gudong.view.ReFreshView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//==================================================================================================================
//   Author :  Shile Wu
//   Date  :  16-8-19
//   Role :    xx
//   Reference documents : xx
//==================================================================================================================
public class HistoryRecordActivity extends Activity implements ReFreshView.OnRefreshListener {
    ReFreshView lv_history;
    LinearLayout ll_history_empty;
    ImageView iv_history_back;
    DatabaseHelper databaseHelper;
    List<Record> records;
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == iv_history_back) {
                finish();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_record);
        lv_history = (ReFreshView) findViewById(R.id.lv_history);
        ll_history_empty = (LinearLayout) findViewById(R.id.ll_history_empty);
        iv_history_back = (ImageView) findViewById(R.id.iv_history_back);

        iv_history_back.setOnClickListener(listener);
        showContent();

    }

    //The map to save sum distance every month
    private Map<Integer, Float> monthSumValue = new HashMap<>();


    private void showContent() {
        /*-begin-201609012-shile.wu-add-for-task2781345-*/
        //old: databaseHelper = new DatabaseHelper(this);
        databaseHelper = DatabaseHelper.getInstance(this);
        /*-end-201609012-shile.wu-add-for-task2781345-*/
        SQLiteDatabase readableDatabase = databaseHelper.getReadableDatabase();
        Cursor query = readableDatabase.query(Constant.DATABASE_TABLE_NAME_SPORT_RECORD,
                new String[]{Constant.DATABASE_TABLE_FIELD_ID, Constant.DATABASE_TABLE_FIELD_TIME,
                        Constant.DATABASE_TABLE_FIELD_DISTANCE,
                        Constant.DATABASE_TABLE_FIELD_AVG_SPEED, Constant.DATABASE_TABLE_FIELD_HOURS,
                        Constant.DATABASE_TABLE_FIELD_AVG_PACE}, null, null, null, null, Constant.DATABASE_TABLE_FIELD_TIME + " desc");
        records = new ArrayList<>();
        int year,month,day,dayTime;
        while (query.moveToNext()) {
            boolean firstOfMonth = false;
            long time = query.getLong(1);
            float distance = query.getFloat(2);
            float speed = query.getFloat(3);
            long hours = query.getLong(4);
            float pace = query.getFloat(5);

            //Save distance to map
            Date date = new Date(time);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh");
            String dateStr = sdf.format(date);
            String[] splitStr = dateStr.split("-");
            year = Integer.parseInt(splitStr[0])-1900;
            month = Integer.parseInt(splitStr[1]);
            day = Integer.parseInt(splitStr[2]);
            dayTime = Integer.parseInt(splitStr[3]);


//            int year = date.getYear();
//            int month = date.getMonth();
            int key = year * 100 + month;
            if (monthSumValue.containsKey(key)) {
                Float saveValue = monthSumValue.get(key);
                monthSumValue.remove(key);
                monthSumValue.put(key, saveValue + distance);
            } else {
                firstOfMonth = true;
                monthSumValue.put(key, distance);
            }

            //Construct new record
            Record record = new Record(query.getInt(0), year,month,day,dayTime, distance, speed, hours, pace, firstOfMonth);
            //Save record to list
            records.add(record);
        }


        /*-begin-20160907-shile.wu-add-for-task2781345-*/
        query.close();
        /*-end-20160907-shile.wu-add-for-task2781345-*/

        //If data is empty show empty view , else show ListView
        if (records.isEmpty()) {
            //Show empty page
            ll_history_empty.setVisibility(View.VISIBLE);
            lv_history.setVisibility(View.INVISIBLE);
        } else {
            //Show ListView
            ll_history_empty.setVisibility(View.INVISIBLE);
            lv_history.setVisibility(View.VISIBLE);

            HistoryRecordListAdapter historyRecordListAdapter = new HistoryRecordListAdapter(this, records, monthSumValue);
            lv_history.setAdapter(historyRecordListAdapter);
            lv_history.setOnRefreshListener(this);
        }
    }

    /*-begin-20160913-shile.wu-add-for-task2781345-*/
    private mHandler mHandler = new mHandler();
    @Override
    public void onRefresh() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    Message message = new Message();
                    message.what = 1;
                    mHandler.sendMessage(message);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public class mHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1){
                lv_history.setOnRefreshComplete();
            }
        }
    }
    /*-end-20160913-shile.wu-add-for-task2781345-*/
}
